<?php
/**
 * User zgh
 * Email 1803897171@qq.com
 * Date 2021/8/1
 **/

namespace app\admin\service;

use app\admin\item\CronLoader;
use app\admin\item\ItemLoader;
use app\admin\pipeline\ItemAdapter;
use app\admin\validate\CronValidate;
use app\common\model\CrontabLogModel;
use app\common\model\CrontabModel;

class CronService
{
    public static function getList($params)
    {
        $pagination = filter_pagination(@$params['page'], @$params['limit']);
        $loader = new  CronLoader();
        $where = $loader->addWhere(['status', '<>', -1])->loadWhere();
        $data = [];
        $query = CrontabModel::where($where)->order(["id" => "desc"]);
        $data['total'] = $query->count();
        $data['dataList'] = [];
        if ($data['total']) {
            $data['dataList'] = $query->limit($pagination['start'], $pagination['limit'])->select()->toArray();
        }
        if (!empty($data['dataList'])) {
            foreach ($data['dataList'] as &$data_row) {
                $loader->clearItem();
                $data_row = $loader->addVal($data_row)->loadItem(2);
            }
        }
        return $data;
    }


    public static function getByID($id)
    {
        $adapter = new  ItemAdapter(CrontabModel::class);
        return $adapter->id($id)->getModel();
    }

    public static function save($params)
    {
        $loader = new CronLoader();
        $data = $loader->addVal($params)->loadItem();
        $data = $loader->clear()->addVal($data)->addVerify(CronValidate::class)->loadItem(0);
        $adapter = new ItemAdapter(CrontabModel::class);
        $res = $adapter->save($data);
        if ($res) {
            return $adapter->getId();
        } else {
            return false;
        }
    }


    public static function del($params)
    {
        $adapter = new ItemAdapter(CrontabModel::class);
        return $adapter->whereUpdate([["id", "in", $params['id']]], ["status" => -1]);
    }

    public static function getLogList($params)
    {
        $pagination = filter_pagination(@$params['page'], @$params['limit']);
        $where = [];
        $data = [];
        $loader = new  ItemLoader();
        $where = $loader->addVal($params)->addWhereSearch("crontab_id", "int")->loadWhere();
        $query = CrontabLogModel::where($where)->order(["id" => "desc"]);
        $data['total'] = $query->count();
        $data['dataList'] = [];
        if ($data['total']) {
            $data['dataList'] = $query->limit($pagination['start'], $pagination['limit'])->append(['status_text'])->select()->toArray();
        }
        return $data;
    }


}